from DrissionPage import ChromiumPage
import time
import random
import json
from config import BASE_DIR
import time
import os

# datas文件夹下创建Today_hot.txt
# file_path = os.path.join(BASE_DIR, 'datas', 'Today_hot.txt')


page = ChromiumPage()

def login():

    # 登录抖音
    url_douying = 'https://www.douyin.com/'
    page.get(url_douying)

    time.sleep(random.randint(2,5))

def get_res():
    url = 'https://www.douyin.com/aweme/v1/web/hot/search/list/'

    page.get(url)

    time.sleep(random.randint(2,5))


    ele = page.ele('xpath://pre')

    # print(ele.text)
    datas = ele.text
    return datas

def parse_datas(datas):
    today_hot = []
    upping_hot = []
    data_dict = json.loads(datas)
     # 写入文件
    file_path = os.path.join(BASE_DIR, 'datas', f'{time.strftime("%Y-%m-%d")}.txt')
    if not os.path.exists(file_path):
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
    # 获取今日热搜榜
    word_list = data_dict.get("data", {}).get("word_list", [])
    print(f"主要热搜排行榜 (共{len(word_list)}条):")
    for i, item in enumerate(word_list, 1):
        word = item.get("word", "")
        hot_value = item.get("hot_value", 0)
        position = item.get("position", i)
        print(f"{position}. {word} (热度值: {hot_value})")
        today_hot.append(f"{position}. {word} (热度值: {hot_value})")
       
        with open(file_path, 'a', encoding='utf-8') as f:
            f.write(f"{position}. {word} (热度值: {hot_value})\n")
    # 获取实时热搜
    trending_list = data_dict.get("data", {}).get("trending_list", [])
    print(f"实时上升热点 (共{len(trending_list)}条):")
    for i, item in enumerate(trending_list, 1):
        word = item.get("word", "")
        print(f"{i}. {word}")
        upping_hot.append(f"{i}. {word}")
        with open(file_path, 'a', encoding='utf-8') as f:
            f.write(f"{i}. {word}\n")
    return today_hot, upping_hot

def main():
    # login()
    datas = get_res()
    today_hot, upping_hot = parse_datas(datas)
    return today_hot, upping_hot



if __name__ == '__main__':
    main()
    

